package com.opal.system.service.impl;

import com.opal.domain.ReturnMessageData;
import com.opal.system.entity.EasyUITree;
import com.opal.system.entity.table.*;
import com.opal.system.mapper.mysql.OpalMenuMapper;
import com.opal.system.mapper.mysql.OpalMenuMapperExtend;
import com.opal.system.mapper.mysql.OpalUserMenuMapper;
import com.opal.system.service.OpalMenuService;
import com.opal.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

@Service
public class OpalMenuServiceImpl implements OpalMenuService {
	@Autowired
	private OpalMenuMapper opalMenuMapper;
	@Autowired
	private OpalUserMenuMapper opalUserMenuMapper;
	@Autowired
	private OpalMenuMapperExtend opalMenuMapperExtend;

	public ReturnMessageData getListOpalMenu(){

		//获取用户id
        Long sessionUserId = UserUtils.getSessionUserId();

        if(sessionUserId==null){
			return new ReturnMessageData(404,"登录已过期，请重新登录！");
		}
		//跟菜单
		List<OpalMenu> parent=new ArrayList<>();
        //获取用户所有菜单
        List<OpalMenu> menus= opalMenuMapperExtend.getMenuByUserId(sessionUserId);
        //存储以id为键的menu
        Map<Long,OpalMenu> maps=new HashMap<>();
        for(OpalMenu menu:menus){
            maps.put(menu.getId(), menu);
            //获取根菜单
            if(menu.getParentId()==0){
                parent.add(menu);
            }
        }

        for(OpalMenu menu:menus){
            OpalMenu opalMenu = maps.get(menu.getParentId());
            if(opalMenu !=null){
                opalMenu.getChildren().add(menu);
            }

        }

		ReturnMessageData r=   new ReturnMessageData();
		r.setList(parent);
		r.setStatu(200);
		return r;
	}

	@Override
	public List<OpalMenu> getOpalMenuByUserIdService(Long userId) {
		return opalMenuMapperExtend.getMenuByUserId(userId);
	}

	@Override
	public List<OpalMenu> getAllMenu() {
		OpalMenuExample ome = new OpalMenuExample();
		ome.createCriteria().andStatusEqualTo(true);
		ome.setOrderByClause("parent_id asc,sort_order desc");
		List<OpalMenu> menus = opalMenuMapper.selectByExample(ome);
		List<OpalMenu> parent=new ArrayList<>();
		//存储以id为键的menu
		Map<Long,OpalMenu> maps=new HashMap<>();
		for(OpalMenu menu:menus){
			maps.put(menu.getId(), menu);
			//获取根菜单
			if(menu.getParentId()==0){
				parent.add(menu);
			}
		}

		for(OpalMenu menu:menus){
			OpalMenu opalMenu = maps.get(menu.getParentId());
			if(opalMenu !=null){
				opalMenu.getChildren().add(menu);
			}

		}
		return parent;
	}

	@Override
	public List<OpalMenu> getMenuAllDataservice() {
		OpalMenuExample ome = new OpalMenuExample();
		ome.setOrderByClause("parent_id asc,sort_order desc");
		List<OpalMenu> list = opalMenuMapper.selectByExample(ome);
		
		return list;
	}

	@Override
	@Transactional("mysqlTransactionManager")
	public ReturnMessageData addMenuService(OpalMenu opalMenu) {
		String urlPath = opalMenu.getUrlPath();
		//判断
		ReturnMessageData rmd=isUrlPath(opalMenu, urlPath,"添加");
		if(rmd !=null) {
			return rmd;
		}
	
		try {
			int i = opalMenuMapper.insertSelective(opalMenu);
			if(i>0) {
				rmd= new ReturnMessageData(200, "添加菜单成功");
			}else {
				rmd= new ReturnMessageData(500, "添加菜单失败");
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			rmd= new ReturnMessageData(500, "添加菜单失败：系统维护中，请稍候再试或联系管理员");
		}
		return rmd;
	}

	@Override
	@Transactional("mysqlTransactionManager")
	public ReturnMessageData updateMenuService(OpalMenu opalMenu) {
		
		String urlPath = opalMenu.getUrlPath();
		//判断
		ReturnMessageData  rmd=isUrlPath(opalMenu, urlPath,"修改");
		if(rmd !=null) {
			return rmd;
		}
		
		try {
			int i = opalMenuMapper.updateByPrimaryKeySelective(opalMenu);
			if(i>0) {
				rmd= new ReturnMessageData(200, "修改菜单成功");
			}else {
				rmd= new ReturnMessageData(500, "修改菜单失败");
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rmd= new ReturnMessageData(500, "修改菜单失败：系统维护中，请稍候再试或联系管理员");
		}
		return rmd;
	}

	private ReturnMessageData isUrlPath(OpalMenu opalMenu, String urlPath,String type) {
		ReturnMessageData rmd=null;
		//判断格式是否正确
		if(urlPath==null) {
			rmd= new ReturnMessageData(500, type+"修改菜单失败：格式不正确");
		}
		if(urlPath.indexOf("/")!=0) {
			 urlPath = "/"+opalMenu.getUrlPath();
			opalMenu.setUrlPath(urlPath);
		}
		if(opalMenu.getIsParent()) {
			if(urlPath.lastIndexOf(".html")<0) {
				urlPath = opalMenu.getUrlPath()+".html";
				opalMenu.setUrlPath(urlPath);
			}
		}
		//判断是否有父菜单
		if(opalMenu.getParentId() ==null) {
			opalMenu.setParentId(0l);
		}else if(opalMenu.getParentId() ==4 ) {
			rmd= new ReturnMessageData(500, type+"菜单失败：不能在 [菜单管理]下添加子菜单！");
		}
		
		//判断自己给自己
		if(opalMenu.getId()==opalMenu.getParentId()) {
			rmd= new ReturnMessageData(500, type+"菜单失败：不能自己给自己添加下级菜单！");
		}
		return rmd;
	}
	
	@Override
	@Transactional("mysqlTransactionManager")
	public ReturnMessageData opalMenuSercice(OpalMenu[] opalMenu) {
		ReturnMessageData rmd = null;
		
		if(opalMenu !=null && opalMenu.length>0) {
			try {
				for(OpalMenu o:opalMenu) {
					int i = opalMenuMapper.deleteByPrimaryKey(o.getId());
					if (i > 0) {
						rmd = new ReturnMessageData(200, "删除菜单成功");
					} else {
						rmd = new ReturnMessageData(500, "删除菜单失败");
					}
				}
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				rmd = new ReturnMessageData(500, "数据库维护中，请稍候再试或联系管理员");
			}
		}
	
		return rmd;
	}

	@Override
	@Transactional("mysqlTransactionManager")
	public ReturnMessageData updateMenuPermissionService(Long userId, Long[] menuIds) {
		//获取用户
		OpalUser sessionUser = UserUtils.getSessionUser();
		if(sessionUser==null){
			return new ReturnMessageData(404,"登录已过期，请重新登录！");
		}

		try{
			//根据用户id删除
			OpalUserMenuExample opalUserMenuExample = new OpalUserMenuExample();
			opalUserMenuExample.createCriteria().andUserIdEqualTo(userId);
			opalUserMenuMapper.deleteByExample(opalUserMenuExample);
			//根据用户id和菜单id封装后插入
			for (Long rId :menuIds){
				OpalUserMenu opalUserMenu = new OpalUserMenu();
				opalUserMenu.setUserId(userId);
				opalUserMenu.setMenuId(rId);
				opalUserMenuMapper.insertSelective(opalUserMenu);
			}

		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new ReturnMessageData(500, "数据库维护中，请稍候再试或联系管理员");
		}
		return new ReturnMessageData(200,"权限修改成功！");
	}

	@Override
	public Object permissionAllMenuService() {
		OpalMenuExample ome = new OpalMenuExample();
		ome.createCriteria().andStatusEqualTo(true);
		ome.setOrderByClause("parent_id asc,sort_order desc");
		List<OpalMenu> menus = opalMenuMapper.selectByExample(ome);

		//暂时就不分上下级关系了：以后有空再做吧，，
		List<EasyUITree> parents=new ArrayList<>();
		for(OpalMenu menu:menus){
			EasyUITree easyUITree =new EasyUITree();
			easyUITree.setParentId(menu.getParentId()+""); //没啥用的
			easyUITree.setText(menu.getName());				//tree的text显示
			easyUITree.setId2(menu.getId());				//这个也没用
			easyUITree.setId(menu.getUrlPath());			//把id设置为路径，所以这里不能重复
			parents.add(easyUITree);
		}

		return parents;
	}


}
